package es.ise.core.mbg.plugins;

import java.util.List;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.internal.util.JavaBeansUtil;

/**
 * Este plugin detecta si la tabla representa alguna de las interfaces definidas
 * en @{see es.ise.core.model}, asociando si hiciera falta algunos de los atributos
 * de la especificación de la interfaz a otro de los atributos del modelo
 * 
 * @author Paco
 *
 */
public class RepresentationsPlugin extends PluginAdapter
{

	/**
	 * {@inheritDoc}
	 * 
	 * @return siempre devuelve <code>true</code> porque no hay comprobaciones que hacer
	 */
	@Override
	public boolean validate(List<String> arg0)
	{
		return true;
	}

	@Override
	public boolean modelBaseRecordClassGenerated(TopLevelClass clazz, IntrospectedTable table)
	{
		String property = table.getTableConfigurationProperty("representations");
		if(property != null && !property.isEmpty())
		{
			for(String representation: property.split("#"))
			{
				String config[] = representation.split("[?]");
				FullyQualifiedJavaType interfaceType = new FullyQualifiedJavaType(String.format("es.ise.core.model.I%s", config[0]));
				clazz.addImportedType(interfaceType);
				clazz.addSuperInterface(interfaceType);
				
				if(config.length > 1 && !config[1].isEmpty())
				{
					for(String assoc: config[1].split("&"))
					{
						String vars[] = assoc.split("=");
						for(Field field: clazz.getFields())
						{
							if(field.getName().equals(vars[1]))
							{
								Method getter = new Method(JavaBeansUtil.getGetterMethodName(vars[0], field.getType()));
								getter.setVisibility(JavaVisibility.PUBLIC);
								getter.setReturnType(field.getType());
								getter.addBodyLine(String.format("return %s();", JavaBeansUtil.getGetterMethodName(vars[1], field.getType())));
								clazz.addMethod(getter);
								
								Method setter = new Method(JavaBeansUtil.getSetterMethodName(vars[0]));
								setter.setVisibility(JavaVisibility.PUBLIC);
								setter.setReturnType(new FullyQualifiedJavaType("void"));
								setter.addParameter(new Parameter(field.getType(), vars[0]));
								setter.addBodyLine(String.format("%s(%s);", JavaBeansUtil.getSetterMethodName(vars[1]), vars[0]));
								clazz.addMethod(setter);
								
								break;
							}
						}
					}
				}
			}
		}
		return true;
	}

	
	
}
